package com.sharainy.contoller;

import com.alibaba.fastjson.JSONObject;

import com.sharainy.pojo.Area;
import com.sharainy.pojo.AreaResponse;
import com.sharainy.pojo.User;
import com.sharainy.service.AreaService;
import com.sharainy.service.MerchantService;
import com.sharainy.util.DateUtil;
import com.sharainy.util.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.sharainy.util.DateUtil.chineseNumber2Int;


@Controller
@RequestMapping("/area")
public class AreaController {
    @Autowired
    private AreaService areaService;
    @Autowired
    private MerchantService merchantService;

    @RequestMapping(value = "/areaPage")
    public String index(Model model,String t){
        model.addAttribute("test",t);
        return "area";
    }
    @RequestMapping("/getAreaList")
    @ResponseBody
    public RestResponse getAreaList(HttpServletRequest request){
        JSONObject jsonMain = new JSONObject();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String companyName = merchantService.selectCompanyName(user.getCompanyid());
        List<Area> level1AreaList = areaService.selectLevel1Area(user.getCompanyid());
        level1AreaList.sort((o1, o2) -> {
            String str1 = o1.getName();
            String str2 = o2.getName();
            str1 = DateUtil.getNumberStr(str1);
            str2 = DateUtil.getNumberStr(str2);
            return (int) (chineseNumber2Int(str1) - chineseNumber2Int(str2));
        });
        for (Area area1:level1AreaList) {
            List<Area> level2AreaList = areaService.selectLevel2Area(area1.getId());
            level2AreaList.sort((o1, o2) -> {
                String str1 = o1.getName();
                String str2 = o2.getName();
                str1 = DateUtil.getNumberStr(str1);
                str2 = DateUtil.getNumberStr(str2);
                return (int) (chineseNumber2Int(str1) - chineseNumber2Int(str2));
            });
            for (Area area2:level2AreaList) {
                List<Area> level3AreaList = areaService.selectLevel3Area(area2.getId());
                level3AreaList.sort((o1, o2) -> {
                    String str1 = o1.getName();
                    String str2 = o2.getName();
                    str1 = DateUtil.getNumberStr(str1);
                    str2 = DateUtil.getNumberStr(str2);
                    return (int) (chineseNumber2Int(str1) - chineseNumber2Int(str2));
                });
                area2.setSonAreaList(level3AreaList);
            }
            area1.setSonAreaList(level2AreaList);
        }
        jsonMain.put("areaList",level1AreaList);
        jsonMain.put("companyName",companyName);
        RestResponse restResponse = RestResponse.succuess();
        restResponse.setData(jsonMain);
        return restResponse;
    }
    @RequestMapping("/searchArea")
    @ResponseBody
    public RestResponse getAreaList(Integer page, Integer limit, String searchName, String searchId, HttpServletRequest request){
        JSONObject jsonMain = new JSONObject();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        long createTime=0;
        String areaIds ="";
        String areaMsg ="";
        String areaName ="";
        List<AreaResponse> areaResponseList = new ArrayList<>();
        List<Area> level1AreaList = areaService.selectLevel1Area(user.getCompanyid());
        for (Area area1:level1AreaList) {
            areaIds="**"+area1.getId()+"";
            createTime=area1.getCreatetime();
            areaName=area1.getName();
            areaMsg=area1.getName();
            List<Area> level2AreaList = areaService.selectLevel2Area(area1.getId());
            if (level2AreaList.size()>0) {
                for (Area area2 : level2AreaList) {
                    createTime=area2.getCreatetime();
                    List<Area> level3AreaList = areaService.selectLevel3Area(area2.getId());
                    if (level3AreaList.size()>0){
                        for (Area area3 : level3AreaList) {
                            createTime=area3.getCreatetime();
                            AreaResponse areaResponse = new AreaResponse();
                            areaResponse.setAreaMsg(areaMsg);
                            areaResponse.setAreaIds(areaIds+"--"+area2.getId()+">>"+area3.getId());
                            areaResponse.setAreaName(areaName+">"+area2.getName()+">"+area3.getName());
                            areaResponse.setCreateTime(DateUtil.timeStamp2Date(createTime+"",""));

                            areaResponseList.add(areaResponse);
                        }
                    }else{
                        AreaResponse areaResponse = new AreaResponse();
                        areaResponse.setAreaMsg(areaMsg);
                        areaResponse.setAreaIds(areaIds+"--"+area2.getId());
                        areaResponse.setAreaName(areaName+">"+area2.getName());
                        areaResponse.setCreateTime(DateUtil.timeStamp2Date(createTime+"",""));
                        areaResponseList.add(areaResponse);
                    }
                }
            }else {
                AreaResponse areaResponse = new AreaResponse();
                areaResponse.setAreaIds(areaIds);
                areaResponse.setAreaMsg(areaMsg);
                areaResponse.setAreaName(areaName);
                areaResponse.setCreateTime(DateUtil.timeStamp2Date(createTime+"",""));
                areaResponseList.add(areaResponse);
            }
        }
        if (searchName!=null&&!"".equals(searchName)){
            Iterator<AreaResponse> it = areaResponseList.iterator();
            while(it.hasNext()){
                AreaResponse areaResponse = it.next();
                if(areaResponse.getAreaName().indexOf(searchName)==-1){
                    it.remove();
                }
            }
        }
        if (searchId!=null&&!"".equals(searchId)){
            Iterator<AreaResponse> it = areaResponseList.iterator();
            while(it.hasNext()){
                AreaResponse areaResponse = it.next();
                if(areaResponse.getAreaIds().indexOf(searchId)==-1){
                    it.remove();
                }else{
                    String responseAreaIds = areaResponse.getAreaIds();
                    if (responseAreaIds.length()>searchId.length()) {
                        String areaStr = responseAreaIds.substring(searchId.length(), searchId.length() + 1);
                        if (Character.isDigit(areaStr.charAt(0))) {
                            it.remove();
                        }
                    }
                }
            }
        }
        for (int i=0;i<areaResponseList.size();i++){
            areaResponseList.get(i).setId(i+1);
        }
        List<AreaResponse> areaResponseList1 = areaResponseList.subList((page-1)*limit, (page-1)*limit+limit>areaResponseList.size()?areaResponseList.size():(page-1)*limit+limit);
        System.out.println(areaResponseList);
        jsonMain.put("areaResponseList1",areaResponseList1);
        jsonMain.put("areaResponseList",areaResponseList);
        RestResponse restResponse = RestResponse.succuess();
        restResponse.setData(jsonMain);
        return restResponse;
    }

    @RequestMapping("/delArea")
    @ResponseBody
    public RestResponse delArea(String id){
        JSONObject jsonMain = new JSONObject();
        try {
            if (id.indexOf(">>") != -1) {
                areaService.deleteLevel3(id.split(">>")[1]);
            } else if (id.indexOf("--") != -1) {
                areaService.deleteLevel2(id.split("--")[1]);
            } else {
                areaService.deleteLevel1(id.replace("**", ""));
            }
            RestResponse restResponse = RestResponse.succuess();
            restResponse.setData(jsonMain);
            return restResponse;
        }catch (Exception e){
            return RestResponse.fail();
        }
    }
    @RequestMapping("/addArea")
    @ResponseBody
    public RestResponse addArea(String level1Area, String level2Area, String level3Area, HttpServletRequest request){
        JSONObject jsonMain = new JSONObject();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        try {
            if (level1Area==null||"".equals(level1Area.replace(" ",""))){
                level1Area="";
            }
            if (level2Area==null||"".equals(level2Area.replace(" ",""))){
                level2Area="";
            }
            if (level3Area==null||"".equals(level3Area.replace(" ",""))){
                level3Area="";
            }
            areaService.addAllArea(level1Area,level2Area,level3Area,user.getCompanyid());
            RestResponse restResponse = RestResponse.succuess();
            restResponse.setData(jsonMain);
            return restResponse;
        }catch (Exception e){
            System.out.println(e);
            return RestResponse.fail();
        }
    }

    @RequestMapping("/modifyArea")
    @ResponseBody
    public RestResponse modifyArea(String areaName, Integer areaType, Integer areaId){
        JSONObject jsonMain = new JSONObject();
        try {
            Area area = new Area();
            area.setName(areaName);
            area.setCreateTime(System.currentTimeMillis()/1000);
            area.setId(areaId);
            if (areaType==1){
                areaService.updateLevel1Area(area);
            }else if (areaType==2){
                areaService.updateLevel2Area(area);
            }else if(areaType==3){
                areaService.updateLevel3Area(area);
            }
            RestResponse restResponse = RestResponse.succuess();
            restResponse.setData(jsonMain);
            return restResponse;
        }catch (Exception e){
            return RestResponse.fail();
        }
    }

}
